package com.xiang.seata.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiang.seata.mapper.AccountMapper;
import com.xiang.seata.model.Account;
import io.seata.core.context.RootContext;
import io.seata.core.model.BranchType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class AccountService {
    @Resource
    private AccountMapper accountMapper;

    /**
     * 减账号金额
     */
    // 参与者  RM (Resource Manager) - 资源管理器
    public void reduce(String userId, int money) {
        String xid = RootContext.getXID();
        BranchType branchType = RootContext.getBranchType();
        boolean gloabTransaction = RootContext.inGlobalTransaction();
        log.info("全局事务ID：{}  --- 模式类型：{}  \n  是否在全局事务中：{}",xid,branchType,gloabTransaction);



        if ("U002".equals(userId)) {
            throw new RuntimeException("this is a mock Exception");
        }

        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new Account().setUserId(userId));
        Account account = accountMapper.selectOne(wrapper);
        account.setMoney(account.getMoney() - money);
        accountMapper.updateById(account);
    }
}
